package com.sailor.exception;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.helpers.FormattingTuple;
import org.slf4j.helpers.MessageFormatter;

/**
 * 支持格式化字符串的自定义运行时异常
 *
 * @author sailor
 */
public class FormativeException extends RuntimeException {


    private String message;
    private transient Throwable throwable;

    public FormativeException() {
        super();
    }

    public FormativeException(String message) {
        this.message = message;
    }

    public FormativeException(Throwable cause) {
        this.throwable = cause;
        this.message = ExceptionUtils.getStackTrace(throwable);
    }

    public FormativeException(String format, Object... arguments) {
        fillInStackTrace();
        this.message = formatMessage(format, arguments);
        if (throwable != null) {
            this.message += System.lineSeparator() + ExceptionUtils.getStackTrace(throwable);
        }
    }

    @Override
    public String getMessage() {
        return message;
    }

    @Override
    public String toString() {
        String className = getClass().getName();
        String msg = getMessage();
        return (StringUtils.isNotEmpty(msg)) ? (className + ":" + msg) : className;
    }

    private String formatMessage(String format, Object... arguments) {
        FormattingTuple formattingTuple = MessageFormatter.arrayFormat(format, arguments);
        this.throwable = formattingTuple.getThrowable();
        return formattingTuple.getMessage();
    }


}
